<template>
  <div class="chart-info pad">
    <el-page-header class="page-header" @back="goBack" :content="title">
    </el-page-header>
    <div class="head" style="margin-bottom: 20px;">
      <span>{{name}}</span>
    </div>
    <el-button v-if="type === 'current'" @click="showQuestionDialog = true" type="primary">
      <i class="el-icon-plus"></i>
      添加标签问题
    </el-button>
    <el-tabs class="m-t-b" type="border-card">
      <el-tab-pane label="标签">
        <el-table :data="labels" v-loading="loading">
          <el-table-column label="标签" prop="nameZ"></el-table-column>
          <el-table-column label="问题排序" prop="sort">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              {{formatTimte(scope.row.createDate)}}
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <span v-if="name === 's1'">
                {{scope.row.enable ? '是' : '否'}}
              </span>
              <el-switch
                v-if="type === 'current' && name !== 's1'"
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="handleChange($event, 1, scope.row)"
              >
              </el-switch>
              <span v-if="type === 'history'">{{scope.row.enable === true ? '是' : '否'}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="问题">
        <el-table stripe :data="questions">
          <el-table-column label="问题" prop="nameZ">
          </el-table-column>
          <el-table-column label="问题排序" prop="sort">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="A" prop="a">
          </el-table-column>
          <el-table-column label="B" prop="b">
          </el-table-column>
          <el-table-column label="C" prop="c">
          </el-table-column>
          <el-table-column label="D" prop="d">
          </el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              {{formatTimte(scope.row.createDate)}}
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                v-if="type === 'current'"
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="handleChange($event, 2, scope.row)"
              >
              </el-switch>
              <span v-if="type === 'history'">{{scope.row.enable === true ? '是' : '否'}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="不定类型">
        <el-table :data="noTypes" v-loading="loading">
          <el-table-column label="题目名称" prop="nameZ"></el-table-column>
          <el-table-column label="问题排序" prop="sort">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              {{formatTimte(scope.row.createDate)}}
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <span v-if="name === 's1'">
                {{scope.row.enable ? '是' : '否'}}
              </span>
              <el-switch
                v-if="type === 'current' && name !== 's1'"
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="handleChange($event, 3, scope.row)"
              >
              </el-switch>
              <span v-if="type === 'history'">{{scope.row.enable === true ? '是' : '否'}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="图片上传类">
        <el-table :data="imgs" v-loading="loading">
          <el-table-column label="题目名称" prop="nameZ"></el-table-column>
          <el-table-column label="问题排序" prop="sort">
            <template slot-scope="scope">
              {{scope.row.sort || '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template slot-scope="scope">
              {{formatTimte(scope.row.createDate)}}
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <span v-if="name === 's1'">
                {{scope.row.enable ? '是' : '否'}}
              </span>
              <el-switch
                v-if="type === 'current' && name !== 's1'"
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="handleChange($event, 4, scope.row)"
              >
              </el-switch>
              <span v-if="type === 'history'">{{scope.row.enable === true ? '是' : '否'}}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="添加标签问题" :visible.sync="showQuestionDialog">
      <el-form :model="question" ref="question" label-position="top">
        <el-form-item label="问题">
          <el-select filterable v-model="question.question" multiple @change="handleSelectChange">
            <el-option v-for="item in selects" :label="item.nameZ" :value="item.labelQuestionId" :key="item.labelQuestionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" v-if="name !== 's1'">
          <el-select filterable v-model="question.label" multiple @change="handleSelectChange">
            <el-option v-for="item in blanks" :value="item.labelQuestionId" :label="item.nameZ" :key="item.labelQuestionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="不定类型选择题">
          <el-select filterable v-model="question.noType" multiple @change="handleSelectChange">
            <el-option v-for="item in noTypeList" :label="item.nameZ" :value="item.labelQuestionId" :key="item.labelQuestionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片上传类">
          <el-select filterable v-model="question.img" multiple @change="handleSelectChange">
            <el-option v-for="item in imgList" :label="item.nameZ" :value="item.labelQuestionId" :key="item.labelQuestionId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设置问题排序">
          <ul class="selected-list">
            <li v-for="(item, index) in selectedList" :key="index">
              <p>{{titleFilter(item.labelQuestionId)}}</p>
              <el-input type="number" v-model="item.sort"/>
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showQuestionDialog = false">取 消</el-button>
        <el-button type="primary" @click="addQuestion('question')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  notifySuccess,
  formatDate,
  cloneObject,
  removeSame
} from '../util'
import {
  getSChartQuestion,
  getAllQuestion,
  addSChartQuestion
} from '../api'

export default {
  name: 'chart-info',
  props: ['type', 'id', 'name'],
  data () {
    return {
      title: '',
      oldQuestions: [],
      loading: true,
      noTypes: [],
      imgs: [],
      noTypeList: [],
      imgList: [],
      showQuestionDialog: false,
      letters: ['A', 'B', 'C', 'D'],
      label: {
        label: '',
        enable: 1
      },
      question: {
        label: [],
        question: [],
        noType: [],
        img: []
      },
      labels: [],
      rules: {
        label: [
          { required: true, message: '标签不能为空!', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '问题不能为空!', trigger: 'blur' }
        ]
      },
      questions: [],
      selects: [],
      selectedList: [],
      blanks: []
    }
  },
  methods: {
    goBack () {
      history.back()
    },
    handleSelectChange () {
      let tempArr = this.question.question.concat(this.question.label).concat(this.question.noType).concat(this.question.img);
      this.selectedList = tempArr.map((item, index) => {
        return {
          labelQuestionId: item,
          enable: 1,
          sort: index + 1
        }
      });
      console.log(this.selectedList)
    },
    addLabel (label) {
      if (this.question.question.length === 0 && this.question.label.length === 0) {
        return this.$message.error('标签和问题不能同时为空!')
      }
    },
    formatTimte (time){
      return formatDate(time)
    },
    handleChange (e, type, data) {
      this.$confirm(`确定${e === false ? '禁用' : '启用'}此标签问题?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let questionList = this.questions.map(item => {
          return {
            labelQuestionId: item.labelQuestionId,
            enable: item.enable === true ? 1 : 0
          }
        })
        let labelList = this.labels.map(item => {
          return {
            labelQuestionId: item.labelQuestionId,
            enable: item.enable === true ? 1 : 0
          }
        })
        let list = questionList.concat(labelList)
        this.handleAddQuestion(list)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
        if (type === 1) {
          for (let i = 0; i < this.labels.length; i ++) {
            if (this.labels[i].labelQuestionId === data.labelQuestionId) {
              return this.labels[i].enable = !e
            }
          }
        } else if (type === 2) {
          for (let i = 0; i < this.questions.length; i ++) {
            if (this.questions[i].labelQuestionId === data.labelQuestionId) {
              return this.questions[i].enable = !e
            }
          }
        } else if (type === 3) {
          for (let i = 0; i < this.noTypes.length; i ++) {
            if (this.noTypes[i].labelQuestionId === data.labelQuestionId) {
              return this.noTypes[i].enable = !e
            }
          }
        } else if (type === 4) {
          for (let i = 0; i < this.imgs.length; i ++) {
            if (this.imgs[i].labelQuestionId === data.labelQuestionId) {
              return this.imgs[i].enable = !e
            }
          }
        }
      })
    },
    addQuestion (form) {
      // if (this.question.question.length === 0 && this.question.label.length === 0) {
      //   return this.$message.error('标签和问题不能同时为空!')
      // };
      this.selectedList.forEach(item => {
        if (item.sort != 0 && !item.sort) {
          return this.$message.error('请设置问题排序')
        }
      });
      let list = this.oldQuestions.concat(this.selectedList);
      list = removeSame(list, 'labelQuestionId');
      list.forEach(item => {
        if (item.sort !== null && !isNaN(item.sort)) {
          item.sort = Number(item.sort)
        }
      });
      this.handleAddQuestion(list)
    },
    fetchQuestions (id) { // 查询表的问题信息
      this.loading = true
      getSChartQuestion(id)
      .then(res => {
        if (res.data.code === 1) {
          // 复制之前的问题信息
          let list = res.data.data || [];
          for (let i = 0; i < list.length; i ++) {
            this.oldQuestions.push({
              labelQuestionId: list[i].labelQuestionId,
              enable: list[i].enable,
              sort: list[i].sort || null
            })
          }
          for (let k = 0; k < list.length; k ++) {
            list[k].enable = list[k].enable === 1 ? true : false
          }
          this.questions = list.filter(item => item.type === 2)
          this.labels = list.filter(item => item.type === 1)
          this.noTypes = list.filter(item => item.type === 3)
          this.imgs = list.filter(item => item.type === 4)
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.$message.error('网络异常!')
        this.loading = false
      })
    },
    fetchAllQuestions (type) { // 查询所有的问题
      getAllQuestion(type)
      .then(res => {
        if (res.data.code === 1) {
          switch (type) {
            case 1:
              this.blanks = res.data.data
              break
            case 2:
              this.selects = res.data.data
              break
            case 3:
              this.noTypeList = res.data.data
              console.log('不定类型', this.noTypeList)
              break
            case 4:
              this.imgList = res.data.data
              console.log('图片上传', this.imgList)
              break
            default:
              break
          }
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    handleAddQuestion (list) {
      addSChartQuestion({
        tableId: Number(this.id),
        list
      })
      .then(res => {
        if (res.data.code === 1) {
          notifySuccess(this)
          this.$router.push('/file/all')
          // this.showLabelDialog = false
          // this.showQuestionDialog = false
          // this.fetchQuestions(Number(this.id))
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    titleFilter (id) {
      let name1 = this.selects.filter(item => item.labelQuestionId === id)[0] || {};
      let name2 = this.blanks.filter(item => item.labelQuestionId === id)[0] || {};
      let name3 = this.noTypeList.filter(item => item.labelQuestionId === id)[0] || {};
      let name4 = this.imgList.filter(item => item.labelQuestionId === id)[0] || {};
      return name1.name || name2.name || name3.name || name4.name
    }
  },
  created () {
    let path = this.$route.meta.path
    this.title = path[path.length - 1]
    this.fetchQuestions(Number(this.id))
    this.fetchAllQuestions(1)
    this.fetchAllQuestions(2)
    this.fetchAllQuestions(3)
    this.fetchAllQuestions(4)
  }
}
</script>
<style lang="scss">
  .chart-info {
    .selected-list li {
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      flex-shrink: 0;
      .el-input {
        width: 100px;
      }
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
</style>
